package com.io.nettyflow.rounter;

import com.io.model.BaseModel;
import com.io.model.RealtimeRptReq;
import com.io.model.RegisterReq;
import com.io.protocol.CommandConstants;
import com.io.util.NettyUtils;
import com.io.webflow.controller.TerminalController;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;


/**
 * Created by yangyx on 2016/7/27.
 * 解析数据接收完毕后的数据传送的一个handler处理
 */
@Component
public class GeneralRouter {

    private static final Logger logger= LoggerFactory.getLogger(GeneralRouter.class);
    @Autowired
    ContextManager contextManager;

    @Autowired
    TerminalController terminalController;
    /**
     *@Author yangyx 【yang_yaxu@launchdesign.com.cn】
     *@Date  2016/8/3 10:25
     *客户端发送的消息根据命令发送到各自的动作
     */
    public void handlerModel(ChannelHandlerContext ctx, BaseModel obj){
        switch(obj.getCommand()){
            case CommandConstants.RegisterReq:
                //登录指令
                terminalController.onRegisterCar(ctx,(RegisterReq) obj);
                break;
            case  CommandConstants.CHANGEPASSWORD:
                //修改密码指令
                if(NettyUtils.checkLoginStatus(ctx)){
                    terminalController.changepassword(ctx,(RegisterReq)obj);
                }
                break;
            case CommandConstants.RealtimeRptReq:
                //实时上报
                RealtimeRptReq realtimeRptReq= (RealtimeRptReq) obj;
                        System.out.println("实时上报数据的时间为===="+realtimeRptReq.ftDay);
                break;
            case CommandConstants.FaultRptReq:
                System.out.println("故障状态命令为======="+obj.getCommand());
                break;
        }
    }

    public void onClientConnected(ChannelHandlerContext ctx) {
        logger.info("CHannelHandlerContext ID为"+ctx.channel().id().asLongText()+"连接成功");
    }

    public void onClientDisconnected(ChannelHandlerContext ctx) {
        logger.debug("客户端断开 channelId : " + ctx.channel().id().asLongText());
        contextManager.printDebug();
        contextManager.removePrincipalOfContext(ctx);
        contextManager.printDebug();
    }

    public void onException(ChannelHandlerContext ctx, Throwable cause) {
        //尽量不要让这种异常发生
        //也就是说,在其他层面捕获并处理所有的异常
        //此处log通常仅供开发调试用
        logger.error("异常发生,关闭客户端！", cause.getMessage());
        cause.printStackTrace();
        ctx.close();
    }

}
